package com.chcit.mobile.mvp.inventory.fragment.pandian;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chcit.mobile.app.base.ScanToolQueryFragment;
import com.google.android.material.textfield.TextInputEditText;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.chcit.custom.view.loader.LoaderStyle;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.custom.view.spinner.DropDownMenu;
import com.chcit.custom.view.text.one.SuperTextView;
import com.chcit.mobile.R;
import com.chcit.mobile.app.utils.TimeDialogUtil;
import com.chcit.mobile.di.component.DaggerInventoryPlanQueryComponent;
import com.chcit.mobile.di.module.CommonModule;
import com.chcit.mobile.di.module.InventoryPlanQueryModule;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.inventory.contract.InventoryPlanQueryContract;
import com.chcit.mobile.mvp.entity.BpartnerBean;
import com.chcit.mobile.mvp.inventory.entity.InventoryBean;
import com.chcit.mobile.mvp.inventory.presenter.InventoryPlanQueryPresenter;
import com.chcit.mobile.mvp.common.adapter.GirdDropDownAdapter;
import com.chcit.mobile.mvp.inventory.adapter.InventoryPlanQueryAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.toast.XToast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class InventoryFirstFragment extends ScanToolQueryFragment<InventoryPlanQueryPresenter> implements InventoryPlanQueryContract.View {

    @BindView(R.id.pr_inventory_plan_dropDownMenu)
    DropDownMenu mDropDownMenu;
    @BindView(R.id.lv_inventory_plan_list)
    RecyclerView mRecyclerView;
    protected String type;

    @Inject
    InventoryPlanQueryAdapter mAdapter;
    private InventoryBean storageBean;
    private int REQUEST_CODE = this.getClass().hashCode();
    private int itemPosition;
    private TextInputEditText tivetPackageNo;
    private TextInputEditText tietLocator;
    private SuperTextView tvDateFrom;
    private SuperTextView tvDateTo;
    private BpartnerBean bpartnerBean;
    private ArrayList<BpartnerBean> bpartners;
    private String headers[] = {"选择日期"};

    public static InventoryFirstFragment newInstance() {
        InventoryFirstFragment fragment = new InventoryFirstFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerInventoryPlanQueryComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .inventoryPlanQueryModule(new InventoryPlanQueryModule(this))
                .commonModule(new CommonModule())
                .build()
                .inject(this);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_inventory_plan_query;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mCommonToolbar.setTitleText("盘点计划查询");
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l -> {
            pop();
            l.setOnClickListener(null);
            if (getActivity() != null) {
                _mActivity.finish();
            }

        });
        vetPackageNo.setHint("请扫码单据号");
        initDropDownMenu();
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext, LoaderStyle.BallSpinFadeLoaderIndicator);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
        getActivity().finish();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        vetPackageNo.setText(barcodeData);
        getData();
    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initRecyclerView();
    }

    private void initRecyclerView() {

        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, 2, Color.WHITE));
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            itemPosition = position;
            if (itemPosition > -1 && mAdapter.getData().size() > 0) {
                mAdapter.setCheckedPosition(itemPosition);
                toDeal(itemPosition);
            }

//                CheckBox checkBox = view.findViewById(R.id.box_puchase_select);
//                checkBox.performClick();
        });
        mRecyclerView.setAdapter(mAdapter);

    }

    private void toDeal(int position) {
        storageBean = mAdapter.getData().get(position);
        startForResult(InventorySecondFragment.newInstance(storageBean), REQUEST_CODE);
    }

    private void initDropDownMenu() {
        final List<View> popupViews = new ArrayList<>();

        //供应商选择
        final ListView wareView = new ListView(mContext);
        bpartners = new ArrayList<>();
        bpartners.add(new BpartnerBean(1, "不限"));
        final GirdDropDownAdapter<BpartnerBean> bpartnerAdapter = new GirdDropDownAdapter<BpartnerBean>(mContext, bpartners);
        wareView.setDividerHeight(0);
        wareView.setAdapter(bpartnerAdapter);
        wareView.setOnItemClickListener((parent, view, position, id) -> {
            bpartnerAdapter.setCheckItem(position);
            bpartnerBean = bpartners.get(position);
            if (position == 0) {
                bpartnerBean = null;
            }
            mDropDownMenu.setTabText(position == 0 ? headers[0] : bpartnerBean.getName());
            mDropDownMenu.closeMenu();
        });

        //日期选择
        final View dateView = getLayoutInflater().inflate(R.layout.pop_date, null);
        tvDateTo = dateView.findViewById(R.id.pop_date_drive);
        tvDateFrom = dateView.findViewById(R.id.pop_date_from);
        TextView ok = dateView.findViewById(R.id.ok);
        tvDateFrom.setCenterString(TimeDialogUtil.getBeforeDay(1));
        tvDateFrom.setOnClickListener(v -> TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->tvDateFrom.setCenterString(s), 6));
        tvDateTo.setOnClickListener(v -> TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->tvDateTo.setCenterString(s), 0));
        tvDateFrom.setOnClickListener(new View.OnClickListener() {
            Calendar calendar = Calendar.getInstance();
            @Override
            public void onClick(View v) {
                TimeDialogUtil.showDatePickerDialog(getActivity(), 3,
                        s->{
                            tvDateFrom.setCenterString(s);
                            ok.performClick();
                        },
                        6,calendar);
            }
        });
        tvDateTo.setOnClickListener(new View.OnClickListener() {
            Calendar calendar = Calendar.getInstance();
            @Override
            public void onClick(View v) {
                TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->{
                    tvDateTo.setCenterString(s);
                    ok.performClick();
                }, 0,calendar);


            }
        });

        ok.setOnClickListener(v -> {
            StringBuffer text = null;
            if(!tvDateFrom.getCenterString().isEmpty()){
                text = new StringBuffer("开始日期：");
                text.append(tvDateFrom.getCenterString()) ;
            }
            if(!tvDateTo.getCenterString().isEmpty()){
                text .append("\n结束日期："+ tvDateTo.getCenterString());
            }

            mDropDownMenu.setTabText(text==null? headers[0] : text.toString());
            mDropDownMenu.closeMenu();
        });


        //商品选择
     /*   final View constellationView = getLayoutInflater().inflate(R.layout.pop_inventory, null);
        tivetPackageNo = constellationView.findViewById(R.id.constellation);//厂家
        tietLocator = constellationView.findViewById(R.id.pop_inventory_locator);
        tietLocator.setVisibility(View.GONE);
        TextView tvConfirm = constellationView.findViewById(R.id.ok);
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = tivetPackageNo.getText().toString();
                mDropDownMenu.setTabText(text.isEmpty() ? headers[1] : text);
                mDropDownMenu.closeMenu();
                onViewClicked(btQuery);
            }
        });

        popupViews.add(wareView);
        popupViews.add(constellationView);
        */
        popupViews.add(dateView);
        final TextView contentView = new TextView(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        contentView.setText("");
        //contentView.setBackgroundColor(getResources().getColor(R.color.gray));
        contentView.setGravity(Gravity.CENTER);
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        final List<String> list = Collections.singletonList("开始日期：" + TimeDialogUtil.getBeforeDay(1));
        mDropDownMenu.setDropDownMenu(list, popupViews, contentView);
        tvDateTo.setRightImageViewClickListener(l -> {
            tvDateTo.setCenterString("");
        });
        tvDateFrom.setRightImageViewClickListener(l -> {
            tvDateFrom.setCenterString("");
        });
      /*  mPresenter.getBpartners(bpartnerBeans -> {
            bpartners.addAll(bpartnerBeans);
            bpartnerAdapter.notifyDataSetChanged();
        });*/

    }

    @OnClick({R.id.bt_common_query})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_common_query:
                mAdapter.getData().clear();
                getData();
                break;
        }
    }

    private void getData() {
        JSONObject data = new JSONObject();
               /* start:0
                    limit:25
                    documentNo:10000
                    productName:1548_713
                    validation: o.Docstatus = 'DR'
                    appSessionID:1542677744838.12*/
        data.put("start", 0);
        data.put("limit", 1000);
        data.put("warehouseId", HttpClientHelper.getSelectWareHouse().getId());

     /*   if (!vetPackageNo.getText().toString().isEmpty()) {
            data.put("documentNo", vetPackageNo.getText().toString());
        }
        if (!tivetPackageNo.getText().toString().isEmpty()) {
          data.put("productName", tivetPackageNo.getText().toString());
        }*/
                /*if (!tietLocator.getText().toString().isEmpty()) {
                    data.put("manufacturer", tietLocator.getText().toString());
                }*/
        if (bpartnerBean != null) {
            data.put("orgID", bpartnerBean.getId());
        }
        if (!tvDateFrom.getCenterTextView().getText().toString().isEmpty()) {
            data.put("dateFrom", tvDateFrom.getCenterTextView().getText().toString());
        }
        if (!tvDateTo.getCenterTextView().getText().toString().isEmpty()) {
            data.put("dateTo", tvDateTo.getCenterTextView().getText().toString());
        }
        mPresenter.getData(data, list -> {

            mAdapter.addData(list);
        });
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            mAdapter.getData().clear();
            mAdapter.notifyDataSetChanged();
        }
    }

}
